package com.bdqn.controller;


import com.bdqn.entity.Category;
import com.bdqn.entity.Employee;
import com.bdqn.param.response.Page;
import com.bdqn.service.CategoryService;
import com.bdqn.util.Constants;
import com.bdqn.util.RespBean;
import com.bdqn.util.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author hunter
 * @since 2022-06-11
 */
@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public RespBean page(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Category> categoryPage = categoryService.pageInfo(page, pageSize);
        return categoryPage != null ? RespBean.ok("获取分类管理列表成功", categoryPage) : RespBean.error("获取分类管理列表失败");
    }

    /**
     * 对分类进行修改操作
     */
    @PutMapping
    public RespBean update(@RequestBody Category category, HttpSession session) {
        String user = (String) session.getAttribute(Constants.LOGIN_SESSION);
        if (user == null) {
            return new RespBean(ResultEnum.AUTH_USER_NOT_LOGIN);
        }
        log.info("获取的创建及修改人的信息为: {}" + user);

        boolean flag = categoryService.saveOrUpdate(category);
        return flag ? RespBean.ok("修改分类成功", flag) : RespBean.error("修改分类失败");
    }

    /**
     * 删除商品分类的操作
     */
    @DeleteMapping
    public RespBean delete(Long ids) {
        boolean falg = categoryService.removeById(ids);
        return falg ? RespBean.ok("分类管理删除成功", falg) : RespBean.error("分类管理删除失败");
    }

    /**
     * 添加菜品/套餐分类
     */
    @PostMapping
    public RespBean addCategory(@RequestBody Category category, HttpSession session) {
        //查询是否已经存在此分类名称
        if (categoryService.checkName(category.getName()) != null) {
            return new RespBean(ResultEnum.REPEAT_PARAM);
        }
        String user = (String) session.getAttribute(Constants.LOGIN_SESSION);
        if (user == null) {
            return new RespBean(ResultEnum.AUTH_USER_NOT_LOGIN);
        }
        log.info("获取的创建及修改人的信息为: {}" + user);
        boolean save = categoryService.save(category);
        return save ? RespBean.ok("添加菜品/套餐分类成功", save) : RespBean.error("添加菜品/套餐分类成功");
    }

    @GetMapping("/list")
    public RespBean list(Integer type) {
        List<Category> categories = categoryService.selectByTypeId(type);
        return categories != null ? RespBean.ok("通过类型id获取的分类信息成功", categories) : RespBean.error("通过类型id获取的分类信息失败");
    }
}
